#include "videowidget.h"
#include "MessageBox.h"
#include <QScroller>
#include <QPainter>
#include <QRubberBand>
#include <QScrollBar>
#include <QDebug>
#include <qevent.h>
#include <VideoPlayerDialog.h>
#include <mainwindow.h>

VideoItemDelegate::VideoItemDelegate(QObject *parent)
    : QStyledItemDelegate(parent)
{
    m_checkedPixmap.load(":/images/check.png");
    m_uncheckedPixmap.load(":/images/uncheck.png");
}

void VideoItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    painter->save();

    // 获取数据
    QPixmap pixmap = qvariant_cast<QPixmap>(index.data(Qt::DecorationRole));

    int nTextTop = 30;
    // 绘制图片
    if (!pixmap.isNull()) {
        QRect iconRect = option.rect;
        iconRect.setHeight(option.rect.height() - 30);
        iconRect.setLeft(option.rect.x() + 10);
        iconRect.setWidth(option.rect.width() - 20);

        // 计算居中位置
        QSize size = pixmap.size().scaled(iconRect.size(), Qt::KeepAspectRatio);
        QPoint pos = QPoint(
            iconRect.x() + (iconRect.width() - size.width()) / 2,
            iconRect.y()
            );

        nTextTop = pos.y() + size.height() + 5;
        painter->drawPixmap(QRect(pos, size), pixmap);

        // 绘制选中状态
        VideoWidget* widget = qobject_cast<VideoWidget*>(parent());
        if (widget && widget->isSelectMode()) {
            if (index.data(VideoModel::SelectRole).toBool())
                painter->drawPixmap(pos.x() + 5, pos.y() + 5,m_checkedPixmap.width()*g_xScale,m_checkedPixmap.width()*g_xScale, m_checkedPixmap);
            else
                painter->drawPixmap(pos.x() + 5, pos.y() + 5,m_checkedPixmap.width()*g_xScale,m_checkedPixmap.width()*g_xScale, m_uncheckedPixmap);
        }
    }

    // 绘制文本
    QRect textRect = option.rect;
    textRect.setTop(nTextTop);
    painter->setPen(Qt::white);
    QFont f = painter->font();
    f.setPixelSize(int(18*g_xScale));
    painter->setFont(f);
    painter->drawText(textRect, Qt::AlignHCenter|Qt::AlignTop, index.data(VideoModel::TextRole).toString());

    painter->restore();
}

VideoWidget::VideoWidget(QWidget *parent)
    : QWidget(parent)
    , m_isSelectMode(false)
    , m_rubberBand(nullptr)
    , m_initialClickState(false)
    , m_initialStateSet(false)
    , m_initialScrollOffset(0)
{
    initUI();
}

void VideoWidget::initUI()
{
    // 创建主布局
    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(0, 0, 0, 0);
    mainLayout->setSpacing(int(10*g_xScale));

    // 创建顶部工具栏
    QWidget* toolbar = new QWidget;
    toolbar->setFixedHeight(int(60*g_yScale));
    QHBoxLayout* toolbarLayout = new QHBoxLayout(toolbar);
    toolbarLayout->setContentsMargins(28, 0, 28, 0);
    toolbarLayout->setSpacing(int(10*g_xScale));

    // 创建选择按钮
    m_selectButton = new TouchButton(tr("选择"));
    m_selectButton->setFixedSize(int(100*g_xScale), int(40*g_yScale));
    m_selectButton->setStyleSheet(
        QString("QPushButton {"
                "    background-color: #48494E;"
                "    border-radius: 4px;"
                "    color: white;"
                "    font: %1px \"微软雅黑\";"
                "}"
                "QPushButton:pressed {"
                "    background-color: #098CFF ;"
                "}").arg(int(18*g_xScale)));

    // 创建全选复选框
    m_selectAllCheckBox = new QCheckBox(tr("全选"));
    m_selectAllCheckBox->setStyleSheet(
        QString(
            "QCheckBox::indicator:unchecked{"
            "width: %1px;"
            "height: %1px; "
            "margin-top:%2px;"
            "    border-image:url(:/images/uncheck.png);"
            "}"
            "QCheckBox::indicator:checked{"
            "width: %1px;"
            "height: %1px; "
            "margin-top:%2px;"
            "     border-image:url(:/images/check.png);"
            "}"
            "QCheckBox{"
            "    color: white;"
            "    font: %3px \"微软雅黑\";"
            "}").arg(int(24*g_xScale)).arg(int(0*g_xScale)).arg(int(18*g_xScale)));


    m_selectAllCheckBox->hide();

    // 创建删除按钮
    m_deleteButton = new TouchButton(tr("删除"));
    m_deleteButton->setFixedSize(int(100*g_xScale), int(40*g_yScale));
    m_deleteButton->setStyleSheet( QString(
                                      "QPushButton {"
                                      "    background-color: #48494E;"
                                      "    border-radius: 4px;"
                                      "    color: white;"
                                      "    font: %1px \"微软雅黑\";"
                                      "}"
                                      "QPushButton:pressed {"
                                      "    background-color: #098CFF ;"
                                      "}").arg(int(18*g_xScale)));
    m_deleteButton->hide();

    // 创建取消按钮
    m_cancelButton = new TouchButton(tr("取消"));
    m_cancelButton->setFixedSize(int(100*g_xScale), int(40*g_yScale));
    m_cancelButton->setStyleSheet(QString(
                                      "QPushButton {"
                                      "    background-color: #48494E;"
                                      "    border-radius: 4px;"
                                      "    color: white;"
                                      "    font: %1px \"微软雅黑\";"
                                      "}"
                                      "QPushButton:pressed {"
                                      "    background-color: #098CFF ;"
                                      "}").arg(int(18*g_xScale)));
    m_cancelButton->hide();

    // 添加到工具栏布局
    toolbarLayout->addStretch();
    toolbarLayout->addWidget(m_selectButton);
    toolbarLayout->addWidget(m_selectAllCheckBox);
    toolbarLayout->addWidget(m_deleteButton);
    toolbarLayout->addWidget(m_cancelButton);

    // 创建列表容器
    QWidget* listContainer = new QWidget;
    m_listLayout = new QVBoxLayout(listContainer);
    m_listLayout->setContentsMargins(0, 0, 0, 0);

    // 创建列表视图
    m_videoListView = new TransparentListView(this);
    m_videoListView->setViewMode(QListView::IconMode);
    m_videoListView->setIconSize(QSize(int(250*g_xScale), int(250*g_yScale)));
    m_videoListView->setGridSize(QSize(int(250*g_xScale), int(250*g_yScale)));
    m_videoListView->setWrapping(true);
    m_videoListView->setResizeMode(QListView::Adjust);
    m_videoListView->setMovement(QListView::Static);
    m_videoListView->setUniformItemSizes(true);
    m_videoListView->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
    m_videoListView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    // 设置视图的大小策略
    m_videoListView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    
    // 设置视图的最小宽度为一个项目的宽度
    m_videoListView->setMinimumWidth(int(250*g_xScale));
    
    m_videoListView->setItemDelegate(new VideoItemDelegate(this));
    m_videoListView->setModel(VideoModel::getInstance());

    // 启用滚动
    QScroller::grabGesture(m_videoListView->viewport(), QScroller::LeftMouseButtonGesture);

    m_listLayout->addWidget(m_videoListView);

    // 添加到主布局
    mainLayout->addWidget(toolbar);
    mainLayout->addWidget(listContainer, 1);

    // 连接信号槽
    connect(m_selectButton, &QPushButton::clicked, this, &VideoWidget::onSelectButtonClicked);
    connect(m_deleteButton, &QPushButton::clicked, this, &VideoWidget::onDeleteButtonClicked);
    connect(m_cancelButton, &QPushButton::clicked, this, &VideoWidget::onCancelButtonClicked);
    connect(m_selectAllCheckBox, &QCheckBox::clicked, this, &VideoWidget::onSelectAllClicked);
}


void VideoWidget::mousePressEvent(QMouseEvent* event)
{
    if (event->button() == Qt::LeftButton) {
        m_pressPos = event->pos();    // 记录按下位置
        m_hasMoved = false;           // 重置移动标记

        if (m_isSelectMode) {
            // 选择模式下的框选逻辑
            if (!m_rubberBand) {
                m_rubberBand = new QRubberBand(QRubberBand::Rectangle, this);
                m_rubberBandOrigin = event->pos();
                m_rubberBand->setGeometry(QRect(m_rubberBandOrigin, QSize()));
                m_rubberBand->show();

                // 保存当前滚动位置
                m_initialScrollOffset = m_videoListView->verticalScrollBar()->value();
                m_initialStateSet = false;

                // 保存所有项目的原始选中状态
                for (int i = 0; i < VideoModel::getInstance()->rowCount(QModelIndex()); ++i) {
                    QModelIndex index = VideoModel::getInstance()->index(i, 0);
                    m_itemOriginalStates[i] = index.data(VideoModel::SelectRole).toBool();
                }
            }
            QPoint pos = m_videoListView->viewport()->mapFrom(this, event->pos());
            QModelIndex index = m_videoListView->indexAt(pos);
            if (index.isValid())
            {
                VideoModel::getInstance()->setSelect(index.row(),!m_itemOriginalStates[index.row()]);
                if (!m_initialStateSet) {
                    m_initialClickState = !m_itemOriginalStates[index.row()];
                    m_initialStateSet = true;
                }
            }
        }
    }
    QWidget::mousePressEvent(event);
}

void VideoWidget::mouseMoveEvent(QMouseEvent* event)
{
    m_hasMoved = true;
    if (m_rubberBand && m_isSelectMode) {
        // 获取列表视图的滚动位置
        int scrollOffset = m_videoListView->verticalScrollBar()->value();

        // 更新框选区域，考虑滚动偏移
        QPoint adjustedOrigin = m_rubberBandOrigin;
        adjustedOrigin.setY(m_rubberBandOrigin.y() - (scrollOffset - m_initialScrollOffset));
        QRect rect = QRect(adjustedOrigin, event->pos()).normalized();
        m_rubberBand->setGeometry(rect);

        // 将窗口坐标转换为视口坐标
        QPoint topLeft = m_videoListView->viewport()->mapFrom(this, rect.topLeft());
        QPoint bottomRight = m_videoListView->viewport()->mapFrom(this, rect.bottomRight());
        QRect viewRect(topLeft, bottomRight);

        // 检查是否需要自动滚动
        QRect viewportRect = m_videoListView->viewport()->rect();
        int mouseY = m_videoListView->viewport()->mapFrom(this, event->pos()).y();

        // 自动滚动速度（每次滚动的像素数）
        const int scrollStep = 10;

        // 在视口顶部和底部创建敏感区域
        const int scrollZone = 50;

        // 向上滚动
        if (mouseY < scrollZone) {
            m_videoListView->verticalScrollBar()->setValue(
                m_videoListView->verticalScrollBar()->value() - scrollStep);
        }
        // 向下滚动
        else if (mouseY > viewportRect.height() - scrollZone) {
            m_videoListView->verticalScrollBar()->setValue(
                m_videoListView->verticalScrollBar()->value() + scrollStep);
        }

        // 更新框选区域内的项目状态
        for (int i = 0; i < VideoModel::getInstance()->rowCount(QModelIndex()); ++i) {
            QModelIndex index = VideoModel::getInstance()->index(i, 0);
            QRect itemRect = m_videoListView->visualRect(index);
            if (viewRect.intersects(itemRect)) {
                if (!m_initialStateSet) {
                    m_initialClickState = !m_itemOriginalStates[i];
                    m_initialStateSet = true;
                }
                VideoModel::getInstance()->setSelect(i, m_initialClickState);
            } else {
                VideoModel::getInstance()->setSelect(i, m_itemOriginalStates[i]);
            }
        }

        updateSelectAllCheckBoxState();
    }
    QWidget::mouseMoveEvent(event);
}

void VideoWidget::mouseReleaseEvent(QMouseEvent* event)
{
    if (event->button() == Qt::LeftButton)
    {
        if (m_isSelectMode)
        {
            if(m_rubberBand)
            {
                m_rubberBand->hide();
                delete m_rubberBand;
                m_rubberBand = nullptr;
                m_itemOriginalStates.clear();
                updateSelectAllCheckBoxState();
            }
        }
        else
        {
            if (!m_hasMoved)
            {
                QPoint pos = m_videoListView->viewport()->mapFrom(this, event->pos());
                QModelIndex index = m_videoListView->indexAt(pos);
                if (index.isValid())
                {
                    QString videoPath = index.data(VideoModel::PathRole).toString();
                    VideoPlayerDialog *dialog = new VideoPlayerDialog(videoPath, MainWindow::getInstance());
                    dialog->exec();
                    delete dialog;
                }
            }
        }
    }
    QWidget::mouseReleaseEvent(event);
}

void VideoWidget::onSelectButtonClicked()
{
    m_isSelectMode = true;
    m_selectButton->hide();
    m_selectAllCheckBox->show();
    m_deleteButton->show();
    m_cancelButton->show();

    QScroller::ungrabGesture(m_videoListView->viewport());
}

void VideoWidget::onDeleteButtonClicked()
{
    if(question(MainWindow::getInstance(),tr("确定要选中的视频文件？"))==0)
    {
        VideoModel::getInstance()->deleteSelectedVideos();
        onCancelButtonClicked();
    }
}

void VideoWidget::onCancelButtonClicked()
{
    m_isSelectMode = false;
    m_selectButton->show();
    m_selectAllCheckBox->hide();
    m_deleteButton->hide();
    m_cancelButton->hide();

    QScroller::grabGesture(m_videoListView->viewport(), QScroller::LeftMouseButtonGesture);

    VideoModel::getInstance()->selectAll(false);
    m_selectAllCheckBox->setChecked(false);
}

void VideoWidget::onSelectAllClicked()
{
    VideoModel::getInstance()->selectAll(m_selectAllCheckBox->isChecked());
}

void VideoWidget::updateSelectAllCheckBoxState()
{
    bool allSelected = true;
    bool anySelected = false;

    for (int i = 0; i < VideoModel::getInstance()->rowCount(QModelIndex()); ++i) {
        QModelIndex index = VideoModel::getInstance()->index(i, 0);
        bool selected = index.data(VideoModel::SelectRole).toBool();
        allSelected &= selected;
        anySelected |= selected;

        if (!selected && anySelected) {
            break;
        }
    }

    m_selectAllCheckBox->setChecked(allSelected);
    m_deleteButton->setEnabled(anySelected);
}

void VideoWidget::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);
    if (m_videoListView) {
        // 计算每个图标项的宽度(包含边距)
        int itemWidth = int(250*g_xScale); // 每个图标项宽度为250
        // 计算可以显示的列数
        int numColumns = width()/itemWidth;
        if(numColumns < 1) numColumns = 1;
        int totalWidth = numColumns * itemWidth;

        // 计算左侧边距
        int leftMargin = (width() - totalWidth) / 2;
        m_listLayout->setContentsMargins(leftMargin,0,0,0);
    }
}

void VideoWidget::setVisible(bool visible)
{
    QWidget::setVisible(visible);
    if(!visible)
    {
        onCancelButtonClicked();
    }
}



bool VideoWidget::isSelectMode()
{
    return m_isSelectMode;
}
